package server;

/**
 * @author Balduin Landolt
 *
 * this class is running in the background of every ServerseitigerClient and is allways counting down.
 * As the client is activ, the countdown is reset.
 * As it reaches 0, a message is sent to the client, asking him, if he's still alife.
 * If yes, the countdown is reset. Otherwhise, if the client gives no answer for a certain time, he gets ckicked.
 */

public class TimeOut extends Thread {

	private ServerseitigerClient parent;
	private long start;
	private long fullTime;
	private boolean requestForAnswerAllreadySent=false;
	
	/**
	 * @param parent the ServerseitigerClient whom owns the Timeout.
	 * 	As the Countdown reaches 0 the parents methodes will be called to react on the Timeout. 
	 * 	(so it's parent whom will be cicked after not being active)
	 * @param milis the time in miliseconds for the timer to reach 0
	 */
	public TimeOut(ServerseitigerClient parent, long milis) {
		super();
		this.parent = parent;
		fullTime=milis;
	}
	
	/**
	 * @param parent the ServerseitigerClient whom owns the Timeout.
	 * 	As the Countdown reaches 0 the parents methodes will be called to react on the Timeout. 
	 * 	(so it's parent whom will be cicked after not being active)
	 * 
	 * the timeout will take a default time (of 5000 milis)
	 */
	public TimeOut(ServerseitigerClient parent) {
		this(parent, 5000);
	}

	@Override
	public void run() {
		while (true){
			start=System.currentTimeMillis();
			while (start+fullTime > System.currentTimeMillis()){
				try {
					sleep(100);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			if (!requestForAnswerAllreadySent){
				parent.askIfClientIsAlife();
				requestForAnswerAllreadySent=true;
				run();
			} else {
				parent.clientIsInactive();
			}
		}
	}

	/**
	 * resets the timer to the specific value that was given to the constructor. 
	 */
	public void resetTimer(){
		start=System.currentTimeMillis();
		requestForAnswerAllreadySent=false;
	}
}
